-- UICommentInput
-- Create by cheny3 Nov/6/2015
-- 增加评论界面

UICommentInput = class("UICommentInput",function()
    return cc.Layer:create()
end)

function UICommentInput.create(commentType)
    return UICommentInput.new(commentType);
end

-- 内部函数声明
local resize;
local sortTitles;
local calcDigit;
local offsetByDigit;

local ONE_LINE_LIMIT = 40;

-- 构造函数
function UICommentInput:ctor(commentType)
    self:setName("UICommentInput");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/comment/CommentInput.csb");
    self:addChild(node);
    self.node = node;

    -- 评论类型
    self.commentType = commentType;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    -- 重绘
    self:redraw();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 适配
    resize(node);
end

-- 修正评论内容
function UICommentInput:adjustContent()
    local index = string.find(self.content, " ", 1)
    -- 去掉头部所有空格
    while index and index == 1 do
        self.content = string.gsub(self.content, " ", "", 1);
        index = string.find(self.content, " ", 1);
    end

    -- 去掉所有的\n
    self.content = string.gsub(self.content, "\n", "");

    if self.content == "" then
        self.content = getLocStr("please_input_comment");
    end

    local retArr = string.fixContent(self.content, TextStyleM.TEXT_SIZE_SMALL2, 420);
    local changeContent = "";
    for index, text in pairs(retArr) do
        changeContent = changeContent .. text;
        if index ~= #retArr then
            changeContent = changeContent .. "\n";
            if string.getByteCount(changeContent) >= self.limitCount then
                -- 超过的直接不要了
                break;
            end
        end
    end
    self.content = changeContent;
end

-- 重绘
function UICommentInput:redraw()
    self.contentLabel = findChildByName(self.node, "CT/content");
    local title = findChildByName(self.node, "CT/title");
    local subhead = findChildByName(self.node, "CT/subhead_left");
    local valueTitle = findChildByName(self.node, "CT/subhead_right");

    -- 限制的字数上限
    self.limitCount = FormulaM.invoke("CALC_COMMENT_WORDS_LIMIT");

    -- 标题
    title:setString(getLocStr("add_comment"));
    TextStyleM.setTitleStyle(title);

    -- 副标题左
    TextStyleM.setSubheadStyle(subhead);
    TextStyleM.setShadowStyle(subhead, cc.size(-0.3, -3.3));
    TextStyleM.setOutlineStyle(subhead, 1.6, TextStyleM.TEXT_OUTLINE_COLOR, true);
    subhead:setString(getLocStr("comment_left_lable"));

    -- 副标题右
    self:redrawSubTitle(valueTitle, "light_blue", self.limitCount);

    -- 位置自适应
    setNextTextPosRightX(subhead, valueTitle, 15);

    -- 创建一个EditBox来接受字符内容
    if isIosPlatform() then
        self:createEditBoxForIos();
    else
        self:createEditBox();
    end
end

-- 绘制标题
function UICommentInput:redrawSubTitle(node, color, value)
    if color == "light_red" then
        TextStyleM.setTextStyle(node, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_LIGHT_RED, true, -3, nil, nil, nil, nil, true);
    else
        TextStyleM.setSubheadStyle(node);
    end

    TextStyleM.setShadowStyle(node, cc.size(-0.3, -3.3));
    TextStyleM.setOutlineStyle(node, 1.6, TextStyleM.TEXT_OUTLINE_COLOR, true);
    node:setString(value);
end

-- ios下创建EditBox
function UICommentInput:createEditBoxForIos()
    local contentLabel = self.contentLabel;

    local editBoxSize = cc.size(400, 250);

    local editBox = ccui.EditBox:create(editBoxSize, "images/ui/login/1.png");
    editBox:setInputMode(cc.EDITBOX_INPUT_MODE_ANY);
    editBox:setFontName(getLocFontName());
    editBox:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editBox:setPlaceholderFontColor(TextStyleM.TEXT_COLOR_BEIGE);
    editBox:setPlaceholderFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editBox:setPlaceHolder(getLocStr("please_input_comment"));
    editBox:setFontColor(TextStyleM.TEXT_COLOR_BEIGE);
    --editBox:setMaxLength(30);
    editBox:setReturnType(cc.KEYBOARD_RETURNTYPE_RETURN);
    self.editBox = editBox;
    contentLabel:getParent():addChild(editBox);

    local function onEditboxEvent(ev)
        if ev == "began" then
        elseif ev == "ended" then
            -- TODO
        elseif ev == "changed" then
            -- TODO
        elseif ev == "return" then
            self.content = self.editBox:getText();
            self:adjustContent();

            -- 设置标题
            local wCount = string.getByteCount(self.content);

            if self.content == getLocStr("please_input_comment") then
                -- 修正字数
                wCount = 0;
            end

            local color = "light_blue";

            if wCount >= self.limitCount then
                color = "light_red";
            end

            -- applyString会转换节点，每次使用前必须重新取
            local function doUpdateSubHead()
                local subhead = findChildByName(self.node, "CT/subhead_left");
                local valueTitle = findChildByName(self.node, "CT/subhead_right");
                local title = findChildByName(self.node, "CT/title");

                -- 副标题左
                TextStyleM.setSubheadStyle(subhead);
                TextStyleM.setShadowStyle(subhead, cc.size(-0.3, -3.3));
                TextStyleM.setOutlineStyle(subhead, 1.6, TextStyleM.TEXT_OUTLINE_COLOR, true);
                subhead:setString(getLocStr("comment_left_lable"));

                -- 左标题偏移
                local offset = offsetByDigit(math.max(self.limitCount - wCount, 0));
                subhead:setPositionX(title:getPositionX() - 30 + offset);

                -- 副标题右
                self:redrawSubTitle(valueTitle, color, math.max(self.limitCount - wCount, 0));

                -- 位置自适应
                setNextTextPosRightX(subhead, valueTitle, 15);
            end
            performWithDelay(self, doUpdateSubHead, 0.1);

            local btnAdd = findChildByName(self.node, "CT/btn_add");
            if wCount > 0 then
                -- 按钮可见
                btnAdd:setBright(true);
                btnAdd:setTouchEnabled(true);
            else
                -- 按钮置灰
                btnAdd:setTouchEnabled(false);
                btnAdd:setBright(false);
            end
        end
    end

    -- 使用系统字
    self.content = "";
    contentLabel:setString(self.content);
    contentLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL2 + 2);
    contentLabel:setTextColor(TextStyleM.TEXT_COLOR_BEIGE);

    editBox:registerScriptEditBoxHandler(onEditboxEvent);
end

-- 其他平台创建EditBox
function UICommentInput:createEditBox()
    local contentLabel = self.contentLabel;

    local editBoxSize = contentLabel:getContentSize();

    local editBox = ccui.EditBox:create(editBoxSize, "images/ui/login/1.png");
    editBox:setInputMode(cc.EDITBOX_INPUT_MODE_ANY);
    editBox:setAnchorPoint(cc.p(0.5, 0.5));
    editBox:setPosition(contentLabel:getPosition());
    editBox:setFontName(getLocFontName());
    editBox:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editBox:setPlaceholderFontColor(TextStyleM.TEXT_COLOR_BEIGE);
    editBox:setPlaceholderFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editBox:setPlaceHolder("");
    editBox:setFontColor(TextStyleM.TEXT_COLOR_BEIGE);
    --editBox:setMaxLength(30);
    editBox:setReturnType(cc.KEYBOARD_RETURNTYPE_DONE);
    self.editBox = editBox;
    contentLabel:getParent():addChild(editBox);

    local function onEditboxEvent(ev)
        if ev == "began" then
            -- 输入被打开
            if self.content == getLocStr("please_input_comment") then
                editBox:setText("");
            else
                editBox:setText(self.content);
            end
            editBox:setVisible(false);
        elseif ev == "ended" then
            -- TODO
        elseif ev == "changed" then
            -- TODO
        elseif ev == "return" then
            -- 输入返回
            editBox:setVisible(true);
            self.content = editBox:getText();

            editBox:setText("");

            self:adjustContent();
            -- 往Label上设置文字
            contentLabel:setString(self.content);

            -- 设置标题
            local wCount = string.getByteCount(self.content);

            if self.content == getLocStr("please_input_comment") then
                -- 修正字数
                wCount = 0;
            end

            local color = "light_blue";

            if wCount >= self.limitCount then
                color = "light_red";
            end

            -- applyString会转换节点，每次使用前必须重新取
            local function doUpdateSubHead()
                local subhead = findChildByName(self.node, "CT/subhead_left");
                local valueTitle = findChildByName(self.node, "CT/subhead_right");
                local title = findChildByName(self.node, "CT/title");

                -- 副标题左
                TextStyleM.setSubheadStyle(subhead);
                TextStyleM.setShadowStyle(subhead, cc.size(-0.3, -3.3));
                TextStyleM.setOutlineStyle(subhead, 1.6, TextStyleM.TEXT_OUTLINE_COLOR, true);
                subhead:setString(getLocStr("comment_left_lable"));

                -- 左标题偏移
                local offset = offsetByDigit(math.max(self.limitCount - wCount, 0));
                subhead:setPositionX(title:getPositionX() - 30 + offset);

                -- 副标题右
                self:redrawSubTitle(valueTitle, color, math.max(self.limitCount - wCount, 0));

                -- 位置自适应
                setNextTextPosRightX(subhead, valueTitle, 15);
            end
            performWithDelay(self, doUpdateSubHead, 0.1);

            local btnAdd = findChildByName(self.node, "CT/btn_add");
            if wCount > 0 then
                -- 按钮可见
                btnAdd:setBright(true);
                btnAdd:setTouchEnabled(true);
            else
                -- 按钮置灰
                btnAdd:setTouchEnabled(false);
                btnAdd:setBright(false);
            end
        end
    end

    -- 使用系统字
    self.content = getLocStr("please_input_comment");
    contentLabel:setString(self.content);
    contentLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL2 + 2);
    contentLabel:setTextColor(TextStyleM.TEXT_COLOR_BEIGE);

    editBox:registerScriptEditBoxHandler(onEditboxEvent);
end

-- 注册点击事件
function UICommentInput:registerTouchEvent()
    local btnCancel = findChildByName(self.node, "CT/btn_cancel");
    local function onCancelClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UICommentInput");
        end
    end
    AddBackEventHandler(self, btnCancel, onCancelClick);
    TextStyleM.setTextStyle(btnCancel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnCancel:setTitleText(getLocStr("btn_text_cancel"));

    local btnBack = findChildByName(self.node, "BT/btn_back");
    AddBackEventHandler(self, btnBack, onCancelClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 返回按钮不可见
    btnBack:setVisible(false);

    local btnAdd = findChildByName(self.node, "CT/btn_add");
    local function onAddClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local limitTime = FormulaM.invoke("CALC_POST_COMMENT_TIME_LIMIT");
            if TimeM.getServerTime() <= (ME.user.dbase:query("last_comment_time") or 0) + limitTime then
                -- 冷却时间
                alert(getLocStr("comment_time_limit"));
                return;
            end
            -- 发布评论
            -- 限制的字数上限
            local limitCount = FormulaM.invoke("CALC_COMMENT_WORDS_LIMIT");
            if self.content and self.content ~= ""
               and self.content ~= getLocStr("please_input_comment") then
                if string.getByteCount(self.content) > limitCount then
                    -- 超过限制字数
                    alert(getLocStr("comment_words_limit_tip"));
                    return;
                end
                -- 有内容且满足条件
                CommentM.postNewComment(self.commentType, self.content);

                -- 关闭当前界面
                UIMgr.getCurrentScene():removeFormByName("UICommentInput");
            end
        end
    end
    btnAdd:addTouchEventListener(onAddClick);
    TextStyleM.setTextStyle(btnAdd, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnAdd:setTitleText(getLocStr("btn_text_add_comment"));

    -- 按钮置灰
    btnAdd:setTouchEnabled(false);
    btnAdd:setBright(false);
end

-- 注册事件处理回调函数
function UICommentInput:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UICommentInput 界面析构清理");
            EventMgr.removeAll("UICommentInput");
        elseif ev == "enter" then
            -- 获得焦点
            EventMgr.register("UICommentInput", event.FOCUS_CHANGED, function(para)
                if para["get"] == "UICommentInput" then
                    -- TODO
                end
            end);
        end
    end);
end

-- 计算一个数是几位数
function calcDigit(num)
    local digit = 1;
    while num / 10 >= 1  do
        num = num / 10;
        digit = digit + 1;
    end
    return digit;
end

-- 根据位数做偏移
function offsetByDigit(num)
    local digit = calcDigit(num);
    local offset = 0;

    if digit == 2 then
        offset = 7;
    elseif digit == 1 then
        offset = 12;
    end

    return offset;
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end